<?php

use Base\AdminController;
use JetBrains\PhpStorm\NoReturn;

class ConfigController extends AdminController
{
    protected string $table = "configs";

    protected string $model = "config";

    #[NoReturn] public function init(): void
    {
        if (Request::input("title")) {
            $this->where[] = ['title','like', '%'.Request::input("title").'%'];
        }
		if (Request::input("id")) {
            $this->where[] = ['group_id','=', Request::input("id")];
        }
        $this->where['sorts'] = 'desc';
        parent::init();
    }

    /**
     * 获取所有的配置
     * @return void
     */
    #[NoReturn] public function getAllAction(): void
    {
        $config = new ConfigModel();
        $data = $config->getAll();
        //@TODO 写入yaml静态文件
        $yamlData = [];
        foreach ($data['dataAll'] as $vo) {
            $yamlData[$vo['name']] = $vo['value'];
        }
        yaml_emit_file(CONFIG_PATH."common.yaml",$yamlData);
        unset($data['dataAll']);
        $this->apiSuccess($data,"获取成功",20000);
    }

    /**
     * 保存配置
     * @return void
     */
    public function saveAction(): void
    {
        try {
            $params = Request::all();
            foreach ($params as $vo) {
                if (isset($vo['data'])) {
                    foreach ($vo['data'] as $v) {
                        ConfigModel::where("id", $v['id'])->update(['value' => $v['value']]);
                    }
                }
            }
            $this->apiSuccess([],"更新成功",20000);
        }catch (Exception $exception) {
            Log::$customFileName = LOG_PATH."/errors/";
            Log::error($exception->getMessage().$exception->getTraceAsString());
            $this->apiError($exception->getMessage());
        }
    }

    /**
     * 文件上传
     * @return void
     */
    public function uploadAction():void
    {
        if (Request::instance()->isPost()) {
            $config = [
                'maxSize' => 4145728,
                'exts' => 'jpg,gif,png,jpeg',
                'rootPath' => './public/uploads/fileTemp/',
                'saveName' => array('uniqid', ''),
                'autoSub'=>false,
            ];
            if (!is_dir($config['rootPath'])) mkdir($config['rootPath'], 0755, true);
            $upload = new Upload($config);
            $uploadInfo = $upload->upload();
            if (!$uploadInfo) $this->apiError($upload->getError());
            $url = getRequestHost(). "/" . $config['rootPath'] . $uploadInfo['file']['savepath'] . $uploadInfo['file']['savename'];
            $result = [
                "url" => $url,
                "index" => Request::input("index"),
                "key"=> Request::input("key")
            ];
            $this->apiSuccess($result ,"上传成功",20000);
        }
    }
}
